import axios from 'axios'
import { ElLoading, ElMessage } from 'element-plus'

let loadingInstance = null

// 创建axios实例
const request = axios.create({
  baseURL: 'http://localhost:2024',  // todo 更改url
  // 超时
  timeout: 10 * 1000
})
// request拦截器
request.interceptors.request.use(
  (config) => {
    //添加请求头
    if (config.uploadFile) {
      config.headers['Content-Type'] = 'multipart/form-data'
    } else {
      config.headers['Content-Type'] = 'application/json;charset=utf-8'
    }
    config.headers['Authorization'] = 'Bearer ' + localStorage.getItem('token') // 让每个请求携带自定义token 请根据实际情况自行修改
    if (config.showLoading) {
      loadingInstance = ElLoading.service({
        lock: true,
        text: '加载中...',
        background: 'rgba(0, 0, 0, 0.7)'
      })
    }
    return config
  },
  (error) => {
    if (loadingInstance) {
      loadingInstance.close()
    }
    ElMessage.error('request.use:' + error.message)
    Promise.reject(error).then()
  }
)

// 响应拦截器
request.interceptors.response.use(
  (res) => {
    if (loadingInstance) {
      loadingInstance.close()
    }

    if (res.data.code === 600) {
      localStorage.removeItem('loginToken')
      localStorage.removeItem('userInfo')
      ElMessage.error('登录失效，请重新登录')
      return Promise.reject('登录失效，请重新登录')
    }

    return Promise.resolve(res)
  },
  (error) => {
    if (loadingInstance) {
      loadingInstance.close()
    }
    ElMessage.error('response.use' + error.message)
    Promise.reject(error).then()
  }
)

export default request
